import os
from datetime import datetime, timedelta
from app import db
from werkzeug.security import generate_password_hash, check_password_hash


# 定义北京时间的UTC偏移量（+8小时）
BEIJING_UTC_OFFSET = timedelta(hours=8)

def beijing_time():
    """返回当前北京时间（UTC+8）"""
    return datetime.utcnow() + BEIJING_UTC_OFFSET

class User(db.Model):
    __tablename__ = 'users'
    id = db.Column(db.Integer, primary_key=True)
    username = db.Column(db.String(64), unique=True, nullable=False)
    nickname = db.Column(db.String(64), default='', nullable=True)
    password_hash = db.Column(db.String(128), nullable=False)
    avatar = db.Column(db.String(256), default='default_avatar.jpg')
    created_at = db.Column(db.DateTime, default=beijing_time)

    # 关联关系
    sent_messages = db.relationship('Message', foreign_keys='Message.sender_id', backref='sender', lazy='dynamic')
    received_messages = db.relationship('Message', foreign_keys='Message.receiver_id', backref='receiver', lazy='dynamic')
    posts = db.relationship('Post', backref='author', lazy='dynamic')  # 新增Post的反向引用
    comments = db.relationship('Comment', backref='author', lazy='dynamic')  # 新增Comment的反向引用


    def set_password(self, password):
        self.password_hash = generate_password_hash(password)

    def check_password(self, password):
        return check_password_hash(self.password_hash, password)

class Post(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    user_id = db.Column(db.Integer, db.ForeignKey('users.id'), nullable=False)
    content = db.Column(db.Text)
    image_url = db.Column(db.String(200))
    created_at = db.Column(db.DateTime, default=beijing_time)
    updated_at = db.Column(db.DateTime, default=beijing_time, onupdate=beijing_time)

    comments = db.relationship('Comment', backref='post', lazy=True, cascade="all, delete-orphan")


class Comment(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    post_id = db.Column(db.Integer, db.ForeignKey('post.id', ondelete='CASCADE'), nullable=False)
    user_id = db.Column(db.Integer, db.ForeignKey('users.id'), nullable=False)
    content = db.Column(db.Text, nullable=False)
    parent_id = db.Column(db.Integer, db.ForeignKey('comment.id'))  # 用于回复功能
    created_at = db.Column(db.DateTime, default=beijing_time)

    replies = db.relationship('Comment', backref=db.backref('parent', remote_side=[id]), lazy=True)


class LoveList(db.Model):
    """恋爱清单模型 - 支持单人私有和情侣共享"""
    __tablename__ = 'love_lists'

    id = db.Column(db.Integer, primary_key=True)
    user_id = db.Column(db.Integer, db.ForeignKey('users.id'), nullable=False)  # 创建者ID
    content = db.Column(db.Text, nullable=False)  # 清单内容（如"一起看电影"）
    is_completed = db.Column(db.Boolean, default=False)  # 是否完成
    completed_at = db.Column(db.DateTime)  # 完成时间
    image_url = db.Column(db.String(256))  # 相关图片URL
    is_shared = db.Column(db.Boolean, default=False)  # 是否共享给情侣
    relationship_id = db.Column(db.Integer, db.ForeignKey('couple_relationships.id'))  # 关联的情侣关系
    created_at = db.Column(db.DateTime, default=beijing_time)
    updated_at = db.Column(db.DateTime, default=beijing_time, onupdate=beijing_time)

    # 关联关系
    creator = db.relationship('User', backref='created_love_items')
    relationship = db.relationship('CoupleRelationship', backref='love_list_items')

    def is_operable_by(self, user_id):
        """判断用户是否有权限操作此清单项"""
        # 1. 创建者永远有权限
        if self.user_id == user_id:
            return True

        # 2. 共享项且用户是情侣关系中的另一方
        if self.is_shared and self.relationship:
            return (self.relationship.user1_id == user_id or
                    self.relationship.user2_id == user_id)

        return False


class Message(db.Model):
    __tablename__ = 'messages'

    id = db.Column(db.Integer, primary_key=True)
    sender_id = db.Column(db.Integer, db.ForeignKey('users.id', ondelete='CASCADE'), nullable=False)
    receiver_id = db.Column(db.Integer, db.ForeignKey('users.id', ondelete='CASCADE'), nullable=False)
    content = db.Column(db.Text, nullable=False)
    parent_id = db.Column(db.Integer, db.ForeignKey('messages.id', ondelete='CASCADE'), nullable=True)  # 新增回复功能
    created_at = db.Column(db.DateTime, default=beijing_time, nullable=False)
    updated_at = db.Column(db.DateTime, default=beijing_time, onupdate=beijing_time, nullable=False)  # 新增更新时间

    # 索引定义（提升查询性能）
    __table_args__ = (
        db.Index('idx_messages_sender', 'sender_id'),
        db.Index('idx_messages_receiver', 'receiver_id'),
        db.Index('idx_messages_parent', 'parent_id'),
    )

class CoupleRelationship(db.Model):
    __tablename__ = 'couple_relationships'
    id = db.Column(db.Integer, primary_key=True)
    user1_id = db.Column(db.Integer, db.ForeignKey('users.id'), nullable=False)
    user2_id = db.Column(db.Integer, db.ForeignKey('users.id'), nullable=False)
    status = db.Column(db.String(20), default='pending')  # pending, accepted, rejected
    created_at = db.Column(db.DateTime, default=beijing_time)
    accepted_at = db.Column(db.DateTime)
    background_image = db.Column(db.String(256))  # 新增：背景图片路径
    # 确保关系不会重复
    __table_args__ = (
        db.CheckConstraint('user1_id < user2_id', name='check_user_order'),
        db.UniqueConstraint('user1_id', 'user2_id', name='unique_couple'),
    )


class CoupleRequest(db.Model):
    __tablename__ = 'couple_requests'
    id = db.Column(db.Integer, primary_key=True)
    sender_id = db.Column(db.Integer, db.ForeignKey('users.id'), nullable=False)
    receiver_id = db.Column(db.Integer, db.ForeignKey('users.id'), nullable=False)
    message = db.Column(db.Text)
    status = db.Column(db.String(20), default='pending')  # pending, accepted, rejected
    created_at = db.Column(db.DateTime, default=beijing_time)
    responded_at = db.Column(db.DateTime)

    # 关联用户
    sender = db.relationship('User', foreign_keys=[sender_id], backref='sent_couple_requests')
    receiver = db.relationship('User', foreign_keys=[receiver_id], backref='received_couple_requests')


class SharedAnniversary(db.Model):
    """共同纪念日模型 - 存储情侣双方共享的纪念日"""
    __tablename__ = 'shared_anniversaries'

    id = db.Column(db.Integer, primary_key=True)
    relationship_id = db.Column(db.Integer, db.ForeignKey('couple_relationships.id'), nullable=False)
    title = db.Column(db.String(128), nullable=False)
    date = db.Column(db.String(32), nullable=False)  # 格式: YYYY-MM-DD
    type = db.Column(db.String(32))  # 例如: 爱情、生活、其他
    description = db.Column(db.Text)
    created_by = db.Column(db.Integer, nullable=False)  # 创建者ID
    created_at = db.Column(db.DateTime, default=beijing_time)
    updated_at = db.Column(db.DateTime, default=beijing_time, onupdate=beijing_time)

    # 关联关系
    relationship = db.relationship('CoupleRelationship', backref='shared_anniversaries')

    def to_dict(self):
        """转换为字典用于API返回"""
        # 计算距离下次纪念日的天数
        today = beijing_time().date()
        anniv_date = datetime.strptime(self.date, '%Y-%m-%d').date()

        # 处理年份，计算最近的纪念日日期
        current_year = today.year
        next_anniv = anniv_date.replace(year=current_year)

        if next_anniv < today:
            next_anniv = next_anniv.replace(year=current_year + 1)

        days_until = (next_anniv - today).days

        return {
            'id': self.id,
            'title': self.title,
            'date': self.date,
            'type': self.type,
            'description': self.description,
            'days_until': days_until,
            'created_by': self.created_by,
            'created_at': self.created_at.isoformat()
        }




class Album(db.Model):
    """相册模型"""
    __tablename__ = 'albums'
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(100), nullable=False)
    description = db.Column(db.Text)
    created_at = db.Column(db.DateTime, default=beijing_time)
    updated_at = db.Column(db.DateTime, default=beijing_time, onupdate=beijing_time)
    is_shared = db.Column(db.Boolean, default=True)  # 是否共享给情侣
    relationship_id = db.Column(db.Integer, db.ForeignKey('couple_relationships.id'))
    creator_id = db.Column(db.Integer, db.ForeignKey('users.id'), nullable=False)
    cover_photo_id = db.Column(db.Integer, db.ForeignKey('photos.id'), nullable=True)
    # 关联
    creator = db.relationship('User', backref='created_albums')
    relationship = db.relationship('CoupleRelationship', backref='albums')
    cover_photo = db.relationship('Photo', foreign_keys=[cover_photo_id], uselist=False)
    photos = db.relationship(
        'Photo',
        backref='album',
        cascade='save-update, merge, delete, delete-orphan',
        passive_deletes=True,  # 允许数据库级联删除
        foreign_keys='Photo.album_id'
    )

    def get_directory_path(self):
        """获取相册的目录路径"""
        user = User.query.get(self.creator_id)
        if not user:
            return None

        from flask import current_app
        return os.path.join(current_app.config['UPLOAD_FOLDER'], str(self.creator_id), str(self.id))

    def delete_directory(self):
        """删除相册目录及其包含的所有文件"""
        import shutil
        dir_path = self.get_directory_path()
        if dir_path and os.path.exists(dir_path):
            try:
                shutil.rmtree(dir_path)
                return True
            except Exception as e:
                print(f"删除相册目录失败: {str(e)}")
        return False


class Photo(db.Model):
    """照片模型"""
    __tablename__ = 'photos'
    id = db.Column(db.Integer, primary_key=True)
    title = db.Column(db.String(100), nullable=False)
    description = db.Column(db.Text)
    filename = db.Column(db.String(255), nullable=False)  # 照片文件名
    date_taken = db.Column(db.Date)  # 拍摄日期
    category = db.Column(db.String(50))  # 分类
    created_at = db.Column(db.DateTime, default=beijing_time)
    updated_at = db.Column(db.DateTime, default=beijing_time, onupdate=beijing_time)
    is_shared = db.Column(db.Boolean, default=True)  # 是否共享给情侣
    album_id = db.Column(db.Integer, db.ForeignKey('albums.id', ondelete='CASCADE'))
    uploaded_by = db.Column(db.Integer, db.ForeignKey('users.id'), nullable=False)

    # 关联
    uploader = db.relationship('User', backref='uploaded_photos')

    def get_file_path(self):
        """获取照片的完整路径"""
        album = Album.query.get(self.album_id)
        if not album:
            return None

        return os.path.join(album.get_directory_path(), self.filename)

    def get_url(self):
        """获取照片的访问URL"""
        return f"/uploads/{self.uploaded_by}/{self.album_id}/{self.filename}"

    def delete_file(self):
        """删除照片文件"""
        file_path = self.get_file_path()
        if file_path and os.path.exists(file_path):
            try:
                os.remove(file_path)
                return True
            except Exception as e:
                from flask import current_app
                current_app.logger.error(f"删除照片文件失败: {str(e)}")
        return False





